from django.shortcuts import render
from .models import customers,orders
from rest_framework.decorators import api_view
from rest_framework.parsers import JSONParser
from django.http import JsonResponse
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from django.core.signing import Signer
from django.core.cache import cache
from datetime import timedelta
from django.shortcuts import render
import random
import string
# Create your views here.

def createtoken(name):
    randomstr=''.join(random.choices(string.ascii_letters,k=8))
    token=Signer().sign(randomstr+name)
    cache.set(f'test_{name}',token,timeout=timedelta(minutes=100).total_seconds())
    return token
# 校验token
def checktoken(request):
    reqtoken=request.META.get('HTTP_TOKEN')
    if reqtoken is None:
        return False,'XXXX'
    untoken=Signer().unsign(reqtoken)
    name=untoken[8:]
    checktoken=cache.get(f'test_{name}')
    if checktoken is None:
        return False,'XXXX'
    return True,name

# 登录
@api_view(["POST"])
def login(request):
    data=JSONParser().parse(request)
    password=data.get('password')
    email=data.get('email')
    if customers.objects.filter(email=email).exists() is False:
        return JsonResponse({
            'code':404,
            'msg':'用户不存在'
        })
    obj=customers.objects.get(email=email)
    if obj.password!=password:
        return JsonResponse({
            'code':400,
            'msg':'用户密码错误'
        })
    token=createtoken(email)
    return JsonResponse({
        'code':200,
        'msg':'登录成功',
        'token':token
    })

